﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using InstrumentCheck.Module;
using InstrumentCheck.DAL;
using System.Net;
using System.Net.Mail;

namespace InstrumentCheck.BLL
{
     public class Form_bll
    {
         private static Form_dal form_dal = new Form_dal();

         public static void Send(ApplyForm form,FormRouting routing,string URL,string strMailFrom)
         {
             form_dal.SendForm(form);
             GenerateMailbodyAndSend(form, routing, URL, strMailFrom);              
         }

         private static void GenerateMailbodyAndSend(ApplyForm form,FormRouting routing,string URL,string strMailFrom)
         {
             string strMailBody = GenerateMailBody(form, URL);
             MailAddress mailFrom = new MailAddress(strMailFrom);
             routing.FormNO = form.FormNO;
             List<MailAddress> list = GetNextFlowMailAddress(routing);
             string strSubject = "";
             switch (form.FormStatus)
             {
                 case FormStatus.Processing:
                     strSubject = "單別 = 校驗申請單：單號 = " + form.FormNO.ToString("0000000000") + "簽核通知";
                     break;
                 case FormStatus.Agree:
                 case FormStatus.Disagree:
                 case FormStatus.WithDraw:
                     strSubject = "[通知] 校驗申請單： 單號 = " + form.FormNO.ToString("0000000000");
                     break;
             }
             
             //下面這段最後需要拿掉的，加上是爲了方便查看debug效果
             //User receiver = routing.Receiver;
             //if(receiver != null)
             //   strSubject += receiver.EmpNO + " - " + receiver.EmpChineseName;

             SendMail(mailFrom, list == null ? null : list.ToArray(), null, strSubject, strMailBody, null);
         }

         public static void Approve(ApplyForm form, FormRouting routing,string URL,string strMailFrom)
         {
             form_dal.ApproveForm(form, routing);
             if (routing.FlowNO == 30) //因為後面要發mail，而mail的body是根據這個status來進行設定的
                 form.FormStatus = FormStatus.Agree;
             GenerateMailbodyAndSend(form, routing, URL, strMailFrom);
         }
         public static void CancelForm(ApplyForm form,string URL,string strMailFrom)
         {
             form_dal.Cancel(form);
             form.FormStatus = FormStatus.WithDraw;
             FormRouting routing = new FormRouting { FormNO = form.FormNO };
             GenerateMailbodyAndSend(form, routing, URL, strMailFrom);
         }
         public static void Reject(ApplyForm form,FormRouting routng,int intRejectTo,string URL,string strMailFrom)
         {
             form_dal.Reject(routng, intRejectTo);
             if (intRejectTo == 0)
                 form.FormStatus = FormStatus.Disagree;
             GenerateMailbodyAndSend(form, routng, URL, strMailFrom);
         }
         public static void Save(ApplyForm form)
         {
             form_dal.SaveForm(form);
         }

         public static List<MailAddress> GetNextFlowMailAddress(FormRouting routing)
         {
             System.Data.DataTable dt = form_dal.GetNextFlowMailAddress(routing);
             if (dt.Rows.Count == 0)
                 return null;

             List<MailAddress> list = new List<MailAddress>();
             foreach (System.Data.DataRow row in dt.Rows)
             {
                 MailAddress address = new MailAddress(row[0].ToString());
                 list.Add(address);
             }

             return list;
         }

         public static ApplyForm GetFormDetailByID(int id)
         {
             return form_dal.GetFormInfoById(id);
         }
         public static List<FormRouting> GetRejectDistinctRouting(int formNO)
         {
             return form_dal.GetDistinctRouting(formNO);
         }

         public static string GenerateMailBody(ApplyForm form,string URL)
         {
             string str = "<html><head><title>Aopen儀器校驗系統</title></head>";
             str += "<body style=\"font-size:9pt\">";
             str += "單號：" + form.FormNO.ToString("0000000000") + "<br>";
             str += "主旨 = [簽核]校驗申請單：";

             User applicant = User_bll.GetUserInfo_bll(form.Applicant.EmpNO);
             str += applicant.DeptNO + " " + applicant.EmpChineseName + " - ";
             str += form.ApplyDate.ToString("yyyy/MM/dd") + " - ";

             Item item = form.Item;
             str += item.AssetNO;

             if (!string.IsNullOrEmpty(item.ChiName))
                 str += " - " + item.ChiName ;
             if (!string.IsNullOrEmpty(item.Spec))
                 str += " - " + item.Spec;
             str += "<br>";

             switch(form.FormStatus)
             {
                 case FormStatus.Processing:
                    str += "簽核結果 = [尚未完成]";
                    break;
                 case FormStatus.Agree:
                    str += "簽核結果 = [已完成][同意]";
                    break;
                 case FormStatus.Disagree:
                    str += "簽核結果 = [已結案][退件]";
                    break;
                 case FormStatus.WithDraw:
                    str += "簽核結果 = [已結案][抽單]";
                    break;
            }

             str += "<p />";
             str += "<a href='" + URL + "/CorrectItem.aspx?ID=" + form.FormID + "'>您有一封表單，請按這裡連結至您的表單 -- 連線主機簡稱（建碁儀器校驗系統）</a>";

             return str;
         }
         public static string GenerateFormHistory(ApplyForm form)
         {
             User Applicant = form.Applicant;
             string strHead = "<table width=\"100%\" borderColor='#b5cff7' border='1'><tr><td align=\"center\" colspan=\"5\" style=\"background-color:#C4EFA1\">表單簽核明細</td></tr><tr>";
             strHead += "<td style=\"background-color:#E7E7FF\">申請者</td><td style=\"background-color:#E7E7FF\">申請時間</td>";
             strHead += "<td style=\"background-color:#E7E7FF\">起始傳送時間</td><td style=\"background-color:#E7E7FF\">結案時間</td>";
             strHead += "<td style=\"background-color:#E7E7FF\">簽核結果</td></tr>";
             strHead += "<tr><td>" + Applicant.EmpChineseName + "</td><td>" + form.ApplyDate.ToString("yyyy/MM/dd HH:mm:ss") + "</td>";
             strHead += "<td>" + form.ApplyDate.ToString("yyyy/MM/dd HH:mm:ss") + "</td>";
             if(form.CloseTime.HasValue)
                 strHead += "<td>" + form.CloseTime.Value.ToString("yyyy/MM/dd HH:mm:ss") + "</td>";
             else
                 strHead += "<td>&nbsp;</td>";
             if (form.FormStatus == FormStatus.Processing)
                 strHead += "<td>簽核中</td>";
             else if (form.FormStatus == FormStatus.Agree)
                 strHead += "<td>同意</td>";
             else if (form.FormStatus == FormStatus.Disagree)
                 strHead += "<td>不同意</td>";
             else if (form.FormStatus == FormStatus.WithDraw)
                 strHead += "<td>已撤銷</td>";
             strHead += "</tr></table>";

             string strLine = "<table width=\"100%\" borderColor='#b5cff7' border='1'><tr><td style=\"background-color:#E7E7FF\">關卡</td>";
             strLine += "<td style=\"background-color:#E7E7FF\">收件人</td><td style=\"background-color:#E7E7FF\">收件時間</td>";
             strLine += "<td style=\"background-color:#E7E7FF\">簽核人</td><td style=\"background-color:#E7E7FF\">簽核時間</td>";
             strLine += "<td style=\"background-color:#E7E7FF\">狀態</td><td style=\"background-color:#E7E7FF\">結果</td></tr>";  //流程的表頭

             List<FormRouting> list = form.FormRoutingHistory;
             for (int i = 0; i < list.Count; i++)
             {
                 FormRouting routing = list[i];
                 User Receiver = routing.Receiver;
                 User Approver = routing.Approver;

                 strLine += "<tr><td>" + routing.FlowName + "</td><td>";
                 strLine += (Receiver.EmpChineseName == "" ? "&nbsp;</td>" : Receiver.EmpChineseName + "</td>");
                 if (routing.ReceiveDate.HasValue)
                     strLine += "<td>" + routing.ReceiveDate.Value.ToString("yyyy/MM/dd HH:mm:ss") + "</td>";
                 else
                     strLine += "<td>&nbsp;</td>";
                 if (routing.ApproveStatus == ApproveStatus.Approved && routing.ApproveResult != ApproveResult.WithDraw && routing.ApproveResult != ApproveResult.OthersApprove)
                 {
                     strLine += "<td>" + Approver.EmpChineseName + "</td>";
                     strLine += "<td>" + routing.ApproverDate.Value.ToString("yyyy/MM/dd HH:mm:ss") + "</td>";
                 }
                 else
                 {
                     strLine += "<td>&nbsp;</td>";
                     strLine += "<td>&nbsp;</td>";
                 }

                 switch (routing.ApproveStatus)
                 {
                     case ApproveStatus.Approved:
                         strLine += "<td>已簽核</td>";
                         break;
                     case ApproveStatus.Approving:
                         strLine += "<td>已傳送</td>";
                         break;
                     default:
                         strLine += "<td>&nbsp;</td>";
                         break;
                 }

                 switch (routing.ApproveResult)
                 {                     
                     case ApproveResult.Approving:
                         strLine += "<td>處理中</td>";
                         break;
                     case ApproveResult.Agree:
                         strLine += "<td>同意</td>";
                         break;
                     case ApproveResult.Disagree:
                         strLine += "<td>不同意</td>";
                         break;
                     case ApproveResult.OthersApprove:
                         strLine += "<td>他人已簽核</td>";
                         break;
                     case ApproveResult.WithDraw:
                         strLine += "<td>已撤銷</td>";
                         break;
                     default:
                         strLine += "<td>&nbsp;</td>";
                         break;
                 }
                 strLine += "</tr>";
                 if (routing.Remark.Trim() != "")
                 {
                     strLine += "<tr><td style=\"background-color:#E7E7FF\">簽核意見：</td>";
                     strLine += "<td colspan=\"6\" align=\"left\">" + routing.Remark + "</td></tr>";
                 }
             }

             return "<table width=\"100%\"><tr><td>" + strHead + "</td></tr><tr><td>" + strLine + "</td></tr></table>";
         }
         
         public static void SendMail(MailAddress mailForm, MailAddress[] mailTo, MailAddress[] mailCC, string subject, string mailBody, params string[] attachmentPath)
         {
             MailMessage myMail = new MailMessage();
             System.Text.UTF8Encoding mailEncoding = new System.Text.UTF8Encoding();
             if (mailForm != null)
                 myMail.From = mailForm;
             else
                 myMail.From = new MailAddress("eformadmin@aopen.com");

             if (mailTo != null && mailTo.Length > 0)
             {
                 foreach (MailAddress mailAddress in mailTo)
                 {
                     myMail.To.Add(mailAddress);
                 }
             }

             if (mailCC != null)
             {
                 foreach (MailAddress mailAddCC in mailCC)
                 {
                     myMail.CC.Add(mailAddCC);
                 }
             }
             myMail.Bcc.Add(new MailAddress("peterchen@aopen.com"));

             myMail.Subject = subject;
             myMail.BodyEncoding = mailEncoding;
             myMail.IsBodyHtml = true;
             myMail.Body = mailBody;

             if (attachmentPath != null && attachmentPath.Length > 0)
             {
                 foreach (string attachment in attachmentPath)
                 {
                     myMail.Attachments.Add(new Attachment(attachment));
                 }
             }

             SmtpClient smtp = new SmtpClient("aoims01");
             smtp.Send(myMail);
         } 
    }
}
